﻿Public Class BEWhere
  Private _booCondSimilar As Boolean
  Private _strOperador As String
  Private _strWhere As String
  Private _booSubSelect As Boolean

  Sub New()
    _booCondSimilar = True
    _strWhere = ""
    _strOperador = "AND"
    _booSubSelect = False
  End Sub

  Sub New(ByVal booSimilar As Boolean)
    _booCondSimilar = booSimilar
    _strWhere = ""
  End Sub

  Public Property CondicaoSimilar() As Boolean
    Get
      Return _booCondSimilar
    End Get
    Set(ByVal value As Boolean)
      _booCondSimilar = value
    End Set
  End Property

  Public Property Where() As String
    Get
      Return IIf(_strWhere.Length > 0, " WHERE " & _strWhere, "")
    End Get
    Set(ByVal value As String)
      _strWhere = value
    End Set
  End Property

  Public Sub AdicionarCondicaoWhereFixo(ByVal strWhere As String)
    _strWhere &= IIf(_strWhere.Length > 0, " AND ", "") & "(" & strWhere & ")"
  End Sub

  Public Sub AdicionarCondicaoWhere(ByVal strCampo As String, ByVal strCondicao As String)
    _strOperador = "AND"
    If (strCampo IsNot Nothing AndAlso strCondicao IsNot Nothing) Then _
        AdicionarCondicaoWhere(strCampo, strCondicao, _booCondSimilar)
  End Sub

  Public Sub AdicionarCondicaoWhereSubSelect(ByVal strCampo As String, ByVal strCondicao As String)
    _strOperador = "AND"
    _booSubSelect = True
    AdicionarCondicaoWhere(strCampo, strCondicao, _booCondSimilar)
  End Sub

  Public Sub AdicionarCondicaoWhere(ByVal arrCampo As String(), ByVal strCondicao As String)
    If (arrCampo IsNot Nothing AndAlso arrCampo.Length > 0 AndAlso strCondicao IsNot Nothing) Then
      _strOperador = "AND"
      For Each strCampo In arrCampo
        If (strCampo IsNot Nothing) Then _
            AdicionarCondicaoWhere(strCampo, strCondicao, _booCondSimilar)
        _strOperador = "OR"
      Next
    End If
  End Sub

  Public Sub AdicionarCondicaoWhere(ByVal strCampo As String, ByVal strCondicao As String, ByVal booSimilar As Boolean)
    If (strCampo IsNot Nothing AndAlso strCondicao IsNot Nothing) Then
      strCondicao = strCondicao.Trim()   '.Replace("'", "''")
      If strCondicao.Length > 0 Then
        If _booSubSelect Then
          strCondicao = strCampo & " IN (" & strCondicao & ")"
          _booSubSelect = False
        ElseIf booSimilar Then
          Dim aCondicao As Array = strCondicao.Split(" ")
          strCondicao = ""
          For intI As Integer = 0 To aCondicao.Length - 1
            If (aCondicao(intI).ToString.Length > 0) Then strCondicao &= strCampo & " LIKE '%" & aCondicao(intI) & "%' AND "
          Next
          strCondicao = strCondicao.Substring(0, strCondicao.Length - 4)
        Else
          strCondicao = strCampo & " = '" & strCondicao & "'"
        End If
        _strWhere &= IIf(_strWhere.Length > 0, " " & _strOperador & " ", "") & "(" & strCondicao & ")"
      End If
    End If
  End Sub

End Class
